<script setup lang="ts">
import {ref} from 'vue'
import type {LoginForm} from "@/views/auth/interfaces";
import {loginAPI} from "@/api/auth";
import {showSuccessToast} from 'vant';
import {setToken} from "@/utils/auth";
import {useRouter} from 'vue-router';
import {useAuthStore} from "@/stores/auth";
import {storeToRefs} from 'pinia';

const username = ref('');
const password = ref('');
const router = useRouter()

const authStore = useAuthStore()
const {setCurrentUser} = authStore

const onSubmit = async (values: LoginForm) => {
  const {data} = await loginAPI(values.username, values.password)
  if (data) {
    showSuccessToast("登录成功")
    setToken(data.token)
    await setCurrentUser()
    router.push('/')
  }
};
</script>

<template>
  <div class="login-box">
    <VanImage src="src/assets/icon/car-bg.svg" style="width: 80vw;margin-top: 20px;"/>

    <van-form @submit="onSubmit" class="login-box-form">
      <VanSpace direction="vertical" style="width: 80vw;" size="1rem">
        <van-field
            v-model="username"
            name="username"
            label="用户名"
            size="large"
            placeholder="用户名或邮箱"
            autocomplete="off"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            size="large"
            placeholder="密码"
            autocomplete="off"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-button block type="primary" native-type="submit">
          提交
        </van-button>
        <div class="login-link">
          <router-link to="/register" class="login-link-register">注册</router-link>
          <router-link to="/forget" class="login-link-forget">忘记密码?</router-link>
        </div>
      </VanSpace>
    </van-form>
  </div>

</template>

<style scoped lang="less">
.login-box {
  height: 100vh;
  background-color: var(--jvyou-school-background-color);
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-box-form {
  margin-top: 20px;
}

.login-link {
  display: flex;
  justify-content: space-between;

  &-register {
    color: #1a8afa;
  }

  &-forget {
    color: #aaa;
  }
}
</style>
